using System;
using System.Collections.Generic;
using UnityEngine;

public abstract class FSMMono<TStateName, TState> : MonoBehaviour where TStateName : Enum where TState : IState
{
	public TStateName currStateName;

	protected TState currState;

	protected Dictionary<TStateName, TState> states;

	public event FSMDelegate<TStateName> OnStateChange;

	private void Update()
	{
		OnUpdate();
	}

	protected virtual void OnUpdate()
    {
        // 不再使用 ref 
        TState reference = currState;
        TState val = default;
        TState referenceValue = reference;
        if (val == null)
        {
            //val = reference;
            //reference = ref val;
            val = referenceValue;
            reference = val;
            if (val == null)
			{
				return;
			}
		}
		reference.OnUpdate();
	}

	public virtual bool ChangeState(TStateName stateName)
	{
		if (states.TryGetValue(stateName, out var value))
        {
            // 不再使用 ref 
            TState reference = currState;
            TState val = default;
            TState referenceValue = reference;
            if (val == null)
            {
                //val = reference;
                //reference = ref val;
                val = referenceValue;
                reference = val;
                if (val == null)
				{
					goto IL_0044;
				}
			}
			reference.OnExit();
			goto IL_0044;
		}
		Debug.LogError($"不存在状态--{stateName}--无法切换。");
		return false;
		IL_0044:
		this.OnStateChange?.Invoke(currStateName, stateName);
		currStateName = stateName;
		currState = value;
		currState.OnEnter();
		return true;
	}
}
